package com.globallogic.vkulyk.NeighbouringNumbersFinder;

import java.util.*;

/**
 * Finds two neighboring numbers in an array with the smallest distance to each
 * other. The index of the first number is outputed to the screen. For example,
 * in the sequence 4 8 6 1 2 9 4 the minimum distance is 1 (between 1 and 2),
 * the function returns the index 3 (of number 1). If exists more than one
 * decision, only a first one is outputted . All input is get from keyboard *
 * 
 * @author Viacheslav Kulyk
 * @version 1.0 20 Jan 2013
 */

public class NeighbouringNumbersFinder {

	private int index = 0;
	private int[] numbers;

	public static void main(String[] args) {
		new NeighbouringNumbersFinder().findNeighboringNumbers();
	}

	private void findNeighboringNumbers() {
		if (getNumbers()) {
			calculateIndex();
			printIndex();
		}
	}

	private boolean getNumbers() {
		boolean result = true;
		Scanner scanner = new Scanner(System.in);
		System.out
				.print("Enter integer numbers, separated with spaces, and press 'Enter' key:");
		String[] words = scanner.nextLine().trim().split("\\s+");
		numbers = new int[words.length];
		int index = 0;
		for (String word : words) {
			try {
				numbers[index++] = Integer.parseInt(word);
			} catch (NumberFormatException nfe) {
				System.out.println("Illegal input '" + word + "'. Must be a number. Exiting.");
				result = false;
				break;
			}
		}
		if (numbers.length < 2) {
			System.out.println("At least 2 numbers required. Exiting.");
			result = false;
		}
		return result;
	}

	private void calculateIndex() {
		int minDistance = 0;
		boolean isFirstLoop = true;
		for (int curIndex = 0; curIndex < (numbers.length - 1); curIndex++) {
			int curDistance;
			if (numbers[curIndex + 1] >= numbers[curIndex]) {
				curDistance = numbers[curIndex + 1] - numbers[curIndex];
			} else {
				curDistance = numbers[curIndex] - numbers[curIndex + 1];
			}
			if (isFirstLoop) {
				minDistance = curDistance;
				index = 0;
				isFirstLoop = false;
			} else if (curDistance < minDistance) {
				minDistance = curDistance;
				index = curIndex;
			}
		}
	}

	private void printIndex() {
		System.out.println(index);
	}

}
